<template>
	<div class="work_info">
		<van-cell-group>
			<van-cell title="售后种类：" :value="category" @click="showCategory = true" isLink />
			<van-cell title="售后原因：" :value="type" @click="showType = true" isLink />
            <van-cell title="商品数量：">
                <van-stepper v-model="refundNum" min=1 :max="goodsNum" @change="onRefundNum"/>
            </van-cell>
			<van-field v-model="refundPrice" label="退款金额：" icon="edit" type="number" input-align="right" />
		</van-cell-group>

		<van-cell-group>
			<van-field v-model="remark" placeholder="请添加说明" icon="edit" type="textarea" :autosize="textareaHeight" />
            <van-cell v-for="(img, i) in images" :key="i">
                <img :src="img.content" width="100%"/>

            </van-cell>
            <van-cell class="image_info">
                <van-uploader :afterRead="imageAfterRead">
                    <div class="image_upload">
                        <van-icon name="camera_full" />
                    </div>
                </van-uploader>
                <div>上传图片</div>
            </van-cell>
		</van-cell-group>
		
		<van-button round type="danger" size="large" @click="saveWorkOrder">提交工单</van-button>
		<van-popup v-model="showCategory" position="bottom">
			<van-picker 
				showToolbar
				:columns="categoryColumns"
				title="选择售后种类"
				@cancel="showCategory = false" 
				@confirm="onCategory"/>
		</van-popup>
		<van-popup v-model="showType" position="bottom">
			<van-picker 
				showToolbar
				:columns="typeColumns"
				title="选择售后原因"
				@cancel="showType = false" 
				@confirm="onType"/>
		</van-popup>
	</div>
</template>

<script>
import {
  Uploader,
  Picker,
  Stepper
} from 'vant';
import {
  WORKORDER_CATEGORY,
  WORKORDER_TYPE,
  WORKORDER_ADD
} from '@/api/user';
import { UPLOAD_FILE } from '@/api/global';

export default {
  props: {
    orderId: [Number, String],
    goodsId: [Number, String],
    goodsPrice: [Number, String],
    goodsNum: [Number, String]
  },
  data() {
    let refundPrice = parseFloat(this.goodsPrice);
    return {
      categoryColumns: [],
      typeColumns: [],

      showCategory: false,
      showType: false,
      categoryIndex: -1,
      typeIndex: -1,
      remark: '',
      images: [],
      refundPrice,
      refundNum: 1,
      textareaHeight: {
          maxHeight: 100
      }
    }
  },

  computed: {
    category() {
      if (this.categoryIndex < 0) {
        return '请选择售后种类';
      }

      return this.categoryColumns[this.categoryIndex].text || '';
    },
    type() {
      if (this.typeIndex < 0) {
        return '请选择售后原因';
      }

      return this.typeColumns[this.typeIndex].text || '';
    }
  },

  watch: {
      refundPrice() {
          // const total = this.goodsPrice * this.refundNum;
          //5.9
            const total = this.accMul(this.refundNum,this.goodsPrice);
          if (this.refundPrice > total) {
              this.refundPrice = total;
          }
      }
  },

  created() {
    this.$reqGet(WORKORDER_CATEGORY).then(res => {
      let v = this;
      let category = res.data.data;

      category.forEach(item => {
        v.categoryColumns.push({
          id: item.id,
          text: item.typename
        });
      });
    });
  },

  methods: {
    imageAfterRead(file) {
      // console.log(file)
      this.images.push(file);
      let fd = new FormData();
      // 将文件转为二进制
      fd.append('file', file.file);
      
      this.$reqPost(UPLOAD_FILE, fd, {dataType: 'json'}).then(res => {
          file.url = res.data.key;
      }).catch(res => {
          this.$dialog.alert({title: '警告', message: res.data.msg});
      });
    },
    onCategory(value, index) {
      this.showCategory = false;
      this.categoryIndex = index;
      this.typeIndex = -1;
      this.typeColumns = [];
      this.$reqGet(WORKORDER_TYPE, {
        category: this.categoryColumns[this.categoryIndex].id
      }).then(res => {
        let v = this;
        let type = res.data.data;

        type.forEach(item => {
          v.typeColumns.push({
            id: item.id,
            text: item.cause
          });
        });
      });
    },

    onType(value, index) {
      if (this.typeColumns.length > 0) {
        this.typeIndex = index;
      } else {
          this.$toast('请先选择售后种类');
      }

      this.showType = false;
    },
    onRefundNum() {
        this.refundPrice = this.accMul(this.refundNum,this.goodsPrice);
    },
    //5.9解决小数精度问题
    accMul(arg1,arg2){
        let m=0;
        let s1=arg1.toString();
        let s2=arg2.toString();
        try{
          m+=s1.split(".")[1].length
          }
          catch(e){}
        try{
          m+=s2.split(".")[1].length
          }
          catch(e){}
        return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
    },
    saveWorkOrder() { 
       if (this.categoryIndex < 0 || this.typeIndex < 0) {
           this.$dialog.alert({title: '警告', message: '请选择售后种类和原因'});
           return;
       } 
      if (this.remark.length <= 0) {
          this.$dialog.alert({title: '警告', message: '请添加申请售后的说明'});
           return;
      }
       let pic = '';
       this.images.forEach(img => {
           pic += img.url + ',';
       });
       this.$reqPost(WORKORDER_ADD, {
            mid: this.user.id,
            oid: this.orderId,
            ogid: this.goodsId,
            type: this.categoryColumns[this.categoryIndex].id,
            prid: this.typeColumns[this.typeIndex].id,
            contents: this.remark,
            pic: pic,
            nums: this.refundNum,
            money: this.refundPrice
        }).then(res => {
            if (res.data.data > 0) {
                this.$toast.success("工单提交成功");
                this.$router.go(-1);
            } else {
                this.$toast.fail("工单提交失败");
            }
        });
    },
  },

  components: {
    [Uploader.name]: Uploader,
    [Picker.name]: Picker,
    [Stepper.name]: Stepper
  }
}
</script>


<style lang="scss" scoped>
.work_info{
    .image_upload{
        position: relative;
        width: 50px;
        height: 50px;
        border: 1px solid $border-color;
        img{
            max-width: 100%;
            max-height: 100%;
        }
        i{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 20px;
            color: $border-color;
        }
    }
    .image_info {
        margin-top: 10px;
        padding: 10px;
    }
    .remark_info {
        padding: 10px;
        width: 92%;
        height: 60px;
        font-size: 12px;
    }
    .van-cell-group {
        margin-bottom: 10px;
    }
}
</style>